<template>
  <section class='f-detail-order'>
    <div class="f-flex-between" style="padding: 10px 15px">
      <p style="color:#666666">
        <span>订单编号：</span>
        <span>{{orderId || '--'}}</span>
      </p>
      <van-button type="primary" round plain size="mini" @click="handleCopy(orderId)">
        <span style="padding: 0 10px">复制订单号</span>
      </van-button>
    </div>

    <ul class="f-steps-group">
      <li class="f-step" v-for="(item,index) in stepList" :key="index">
        <div class="f-icon">
          <van-icon name="circle" color="#3178F4" v-if="index == 0" style="background:#3178F4;border-radius:50%" />
          <van-icon name="success" color="#a9a9a9" v-else />
          <p v-if="[1,4,5,6,7].includes(item.state)" :class="{'f-line': index + 1 < stepList.length}" style="height: 30px;"></p>
          <p v-else :class="{'f-line': index + 1 < stepList.length}" style="height: 45px;"></p>
        </div>
        <section style="flex:1">
          <div class="f-flex-between">
            <p style="font-size:14px" :style="{'color': statusColor[item.state]}">
              {{statusForm[item.state]}}
            </p>
            <p>{{ getDateTime(item.createdTime)[6] }}</p>
          </div>
          <div class="f-flex-between f-mt-05" style="color:#2C71F0;" v-if="item.chargesOrderId"
            @click="toBenefit(item.chargesOrderId)">
            <p>佣金订单：{{item.chargesOrderId}}</p>
            <p class="f-flex-between" style="width:95px">
              <span>佣金：{{item.amount / 100}}元</span>
              <van-icon name="arrow" />
            </p>
          </div>
          <div class="f-mt-05" v-if="item.state == 2">失败原因：{{item.content || '--'}}</div>
          <div class="f-mt-05 f-flex-between" v-if="item.relationId" style="color:#2C71F0;"
            @click="toUploadDetail(item.relationId)">
            <p>关联订单：{{item.relationId || '--'}}</p>
            <van-icon name="arrow" />
          </div>
        </section>
      </li>
    </ul>

    <van-cell class="f-mt-15" title="关联商品" :value="formData.goodsName" />
    <van-cell title="订单来源" :value="formData.shopName" />

    <van-cell class="f-mt-15" title="激活号码" :value="formData.phone" />
    <van-cell title="机主姓名" :value="formData.idcardName" />

    <van-cell class="f-mt-15" v-if="formData.extraTxt1Name" :title="formData.extraTxt1Name" :value="formData.withExtraTxt1"
      readonly />
    <van-cell v-if="formData.extraTxt2Name" :title="formData.extraTxt2Name" :value="formData.withExtraTxt2" readonly />
    <van-cell v-if="formData.extraTxt3Name" :title="formData.extraTxt3Name" :value="formData.withExtraTxt3" readonly />

    <p class="f-mt-15 f-title">上传开卡照片</p>
    <van-cell-group class="f-flex-row" style="flex-wrap:wrap">
      <van-field v-if="formData.withImg1" name="withImg1" style="width:50%;padding:10px" @click="imagePreview(formData.withImg1)">
        <template #input>
          <section>
            <img class="f-img1" :src="formData.withImg1" alt="">
            <p class="f-center" style="font-size: 12px;color: #424242;">身份证人像面</p>
          </section>
        </template>
      </van-field>
      <van-field v-if="formData.withImg2" name="withImg2" style="width:50%;padding:10px" @click="imagePreview(formData.withImg2)">
        <template #input>
          <section>
            <img class="f-img1" :src="formData.withImg2" alt="">
            <p class="f-center" style="font-size: 12px;color: #424242;">身份证国徽面</p>
          </section>
        </template>
      </van-field>
      <van-field v-if="formData.withImg3" name="withImg3" style="width:50%;padding:10px" @click="imagePreview(formData.withImg3)">
        <template #input>
          <section>
            <img class="f-img1" :src="formData.withImg3" alt="">
            <p class="f-center" style="font-size: 12px;color: #424242;">手持身份证照</p>
          </section>
        </template>
      </van-field>
      <van-field v-if="formData.withImg4" name="withImg4" style="width:50%;padding:10px" @click="imagePreview(formData.withImg4)">
        <template #input>
          <section>
            <img class="f-img1" :src="formData.withImg4" alt="">
            <p class="f-center" style="font-size: 12px;color: #424242;">手持反诈说明</p>
          </section>
        </template>
      </van-field>
      <van-field v-if="formData.withExtraImg1" name="withExtraImg1" style="width:50%;padding:10px"
        @click="imagePreview(formData.withExtraImg1)">
        <template #input>
          <section>
            <img class="f-img1" :src="formData.withExtraImg1" alt="">
            <p class="f-center" style="font-size: 12px;color: #424242;">{{formData.extraImg1Name || '补充图片'}}</p>
          </section>
        </template>
      </van-field>
      <van-field v-if="formData.withExtraImg2" name="withExtraImg2" style="width:50%;padding:10px"
        @click="imagePreview(formData.withExtraImg2)">
        <template #input>
          <section>
            <img class="f-img1" :src="formData.withExtraImg2" alt="">
            <p class="f-center" style="font-size: 12px;color: #424242;">{{formData.extraImg2Name || '补充图片'}}</p>
          </section>
        </template>
      </van-field>
      <van-field v-if="formData.withExtraImg3" name="withExtraImg3" style="width:50%;padding:10px"
        @click="imagePreview(formData.withExtraImg3)">
        <template #input>
          <section>
            <img class="f-img1" :src="formData.withExtraImg3" alt="">
            <p class="f-center" style="font-size: 12px;color: #424242;">{{formData.extraImg3Name || '补充图片'}}</p>
          </section>
        </template>
      </van-field>
    </van-cell-group>

    <section class="f-btn-box" v-if="currentState != 2">
      <van-button v-if="currentState  == 1 " style="width:40%" round type="primary" plain @click="openInspect(1)">去审核</van-button>
      <van-button v-if="currentState  == 1 " style="width:40%" round type="primary" @click="showForward = true">去转发</van-button>
      <van-button v-if="currentState  == 5 " style="width:60%" round type="primary" plain @click="openInspect(2)">去分佣</van-button>
      <van-button v-if="currentState  == 3 || currentState  == 8 || currentState  == 9" style="width:40%" round type="primary"
        plain @click="openInspect(3)">再次分佣</van-button>
      <van-button v-if="currentState  == 3 || currentState  == 8 || currentState  == 9" style="width:40%" round type="danger"
        plain @click="openInspect(4)">佣金核减</van-button>
    </section>

    <van-popup v-model:show="showInspect" closeable position="bottom" close-icon-position="top-left"
      @closed="closePopup('inspectForm')">
      <p class="f-popup-title">
        {{ showInspectType == 1 ? '资料审核': showInspectType == 2? '订单分佣':  showInspectType == 3? '再次分佣': '佣金核减'}}
      </p>
      <van-form ref="formRef" @submit="submitInspect" label-width="70px" validate-trigger="onSubmit">
        <van-cell-group>
          <van-field name="shopName" label="审核结果" v-if="showInspectType == 1">
            <template #input>
              <van-radio-group v-model="inspectForm.opResult" direction="horizontal">
                <van-radio :name="1" icon-size="16px">通过</van-radio>
                <van-radio :name="-1" icon-size="16px">拒绝</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <template v-if="inspectForm.opResult == 1">
            <van-field name="shopName" label="佣金方式" v-if="showInspectType != 4">
              <template #input>
                <van-radio-group v-model="inspectForm.checked" direction="horizontal">
                  <van-radio :name="1" icon-size="16px">按佣金政策</van-radio>
                  <van-radio :name="2" icon-size="16px">手动填写佣金</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            <van-field v-if="inspectForm.checked == 1" v-model="inspectForm.recordName" name="shopName" label="佣金政策"
              placeholder="请选择佣金政策" :rules="[{ required: true, message: '请选择佣金政策' }]" right-icon="arrow" readonly
              @click="openPicker('选择佣金政策')"></van-field>
            <van-field v-if="inspectForm.checked == 1" v-model="inspectForm.income" name="amount" label="佣金金额"
              placeholder="请填写佣金金额" readonly>
              <template #extra>
                <p>元</p>
              </template>
            </van-field>
            <van-field v-if="inspectForm.checked == 2 && showInspectType != 4" v-model="inspectForm.amount" name="amount"
              label="佣金金额" placeholder="请填写佣金金额" :rules="[ {required: true, message: '请填写佣金金额' }]" type="number">
              <template #extra>
                <p>元</p>
              </template>
            </van-field>
            <van-field v-if="showInspectType == 4" v-model="inspectForm.amount" name="amount" label="核减金额" placeholder="请填写核减金额"
              :rules="[ {required: true, message: '请填写核减金额' }]" type="number">
              <template #extra>
                <p>元</p>
              </template>
            </van-field>
          </template>

          <van-field v-model="inspectForm.content" name="content" label="备注信息" placeholder="请填写备注信息"></van-field>
          <van-field v-model="inspectForm.password" name="shopName" label="密码验证" placeholder="请填写您的登陆密码"
            :type="inspectForm.showPassword?'':'password'"
            :rules="[ {required: true, message: '请填写您的登陆密码' },{ validator: validatorPassword, message: '密码错误' }]">
            <template #right-icon>
              <van-icon v-show="!inspectForm.showPassword" name="closed-eye" @click="inspectForm.showPassword = true" />
              <van-icon v-show="inspectForm.showPassword" name="eye-o" @click="inspectForm.showPassword = false" />
            </template>
          </van-field>

        </van-cell-group>

        <div class="f-popup-btn">
          <van-button block type="primary" native-type="submit">确定</van-button>
        </div>
      </van-form>
    </van-popup>

    <van-popup v-model:show="showForward" closeable position="bottom" close-icon-position="top-left">
      <p class="f-popup-title">资料转发</p>
      <van-form ref="formRef" @submit="submitForward" label-width="70px">
        <van-cell-group style="padding: 20px 0 50px 0">
          <van-field v-model="forwardForm.shopName" name="shopName" label="供应商" placeholder="请选择要转发的供应商"
            :rules="[{ required: true, message: '请选择要转发的供应商' }]" right-icon="arrow" readonly @click="openPicker('选择供应商')" />
          <van-field v-model="forwardForm.goodsName" name="goodsName" label="供应商商品" placeholder="请选择供应商商品"
            :rules="[{ required: true, message: '请选择供应商商品' }]" right-icon="arrow" readonly @click="openPicker('选择供应商商品')" />
        </van-cell-group>

        <div class="f-popup-btn">
          <van-button block type="primary" native-type="submit">确定</van-button>
        </div>
      </van-form>
    </van-popup>

    <van-popup v-model:show="showPicker" position="bottom">
      <p class="f-popup-title">{{pickerTitle}}</p>
      <section v-if="pickerTitle == '选择供应商'">
        <van-picker ref="pickerRef" v-model="selectShopId" :columns="mySupplierList" :columns-field-names="customFieldName"
          :show-toolbar="false" />
        <div class="f-popup-btn">
          <van-button block type="primary" @click="handlePicker('选择供应商')">确定</van-button>
        </div>
      </section>

      <van-cascader v-if="pickerTitle == '选择供应商商品'" v-model="cascaderValue" :options="goodsList" :field-names="fieldNames"
        :show-header="false" @finish="handleCascader" />

      <section v-if="pickerTitle == '选择佣金政策'">
        <van-picker ref="incomeRef" v-model="selectRecordId" :columns="incomeList" :columns-field-names="incomeFieldName"
          :show-toolbar="false" />
        <div class="f-popup-btn">
          <van-button block type="primary" @click="handlePicker('选择佣金政策')">确定</van-button>
        </div>
      </section>
    </van-popup>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import { successDeal, getStore, warningDeal, getDateTime } from '@/utils/utils';
import { showImagePreview, closeToast } from 'vant';
import hexMD5 from "@/utils/md5.min.js"
import api from '../api'

export default {
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const pickerRef = ref()
    const incomeRef = ref()

    const state = reactive({
      orderId: '',
      formData: {},

      showInspect: false,
      showInspectType: 1,
      inspectForm: {
        "amount": "",
        "content": "",
        "opResult": 1,
        "orderId": "",
        checked: 1
      },
      inspectFormDeep: {},

      showForward: false,
      forwardForm: {},
      mySupplierList: [],

      selectRecordId: [],
      incomeList: [],
      incomeFieldName: {
        text: 'recordName',
        value: 'recordId',
        children: 'children'
      },

      showPicker: false,
      pickerTitle: '',
      selectShopId: [],
      mySupplierList: [],
      customFieldName: {
        text: 'shopName',
        value: 'shopId',
        children: 'children'
      },

      goodsList: [],
      cascaderValue: '',
      fieldNames: {
        text: 'goodsName',
        value: 'goodsId',
        children: 'goodsInfoList',
      },

      currentState: '',
      stepList: [],
      statusForm: {
        '1': '待审核',
        '2': '审核失败',
        '3': '审核成功',
        '4': '待上级审核',
        '5': '上级审核成功（待分佣）',
        '6': '资料上传成功',
        '7': '已转发',
        '8': '分佣成功',
        '9': '佣金核减',
      },
      statusColor: {
        '1': '#FF8030',
        '2': '#FF2333',
        '3': '#4BBC1F',
        '4': '#FF8030',
        '5': '#FF8030',
        '6': '#000000',
        '7': '#000000',
        '8': '#4BBC1F',
        '9': '#FF2A2A',
      }
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '订单详情',
        show: true,
        left: true,
        leftType: 'back',
        right: false,
        rightText: '',
      });

      state.orderId = route.query.orderId
      state.inspectFormDeep = JSON.parse(JSON.stringify(state.inspectForm))

      getOrderDetail(state.orderId)
      getOrderRecord(state.orderId)
      getSupplierList()
    })

    const getOrderDetail = (orderId) => {
      let json = {
        orderId
      }
      api.orderInspectDetail(json).then(res => {
        state.formData = res.data
        getIncomeList()
      })
    }

    const getIncomeList = () => {
      let json = {
        "endTime": "",
        "goodsId": `${state.formData.goodsId},all`,
        "orderBy": "",
        "page": 1,
        "recordName": "",
        "shopId": getStore('USER_INFO').companyId,
        "size": 100,
        "startTime": ""
      }
      api.incomeList(json).then(res => {
        state.incomeList = res.data.list
      })
    }

    const getSupplierList = () => {
      api.mySupplierList().then(res => {
        state.mySupplierList = res.data
      })
    };

    const getOrderRecord = (orderId) => {
      let json = {
        orderId
      }
      api.orderRecord(json).then(res => {
        state.stepList = res.data
        state.currentState = res.data[0].state
      })
    }

    function handleCopy(value) {
      const input = document.createElement('input');
      document.body.appendChild(input);
      input.setAttribute('value', value);
      input.select();
      if (document.execCommand('copy')) {
        document.execCommand('copy');
        successDeal('复制成功！')
      }
      document.body.removeChild(input);
    }

    const imagePreview = (src) => {
      showImagePreview([src]);
    }

    const validatorPassword = (val) =>
      new Promise((resolve) => {
        let json = {
          password: hexMD5(val)
        }
        api.confirmPassword(json).then(res => {
          resolve(true)
        }).catch(err => {
          resolve(false)
        })
      });

    const submitInspect = () => {
      let data = JSON.parse(JSON.stringify(state.inspectForm))
      let json = {
        "amount": 0,
        "content": data.content,
        "opResult": data.opResult,
        "orderId": state.orderId
      }

      let num = 0
      if (json.opResult == 1) {
        if (data.checked == 1) {
          num = JSON.parse(JSON.stringify(data.income))
          json.amount = data.income * 100
        } else {
          num = JSON.parse(JSON.stringify(data.amount))
          json.amount = data.amount * 100
        }

        if (json.amount < 0) {
          warningDeal('金额不能为负数！')
          return
        }

        if (num.indexOf('.') > -1) {
          let len = num.toString().split('.').pop().length;
          console.log(len)
          if (len > 2) {
            warningDeal('金额只能保留2位小数！');
            return
          }
        }
      }

      if (state.showInspectType == 1) {
        // 资料审核
        api.orderApprove(json).then(res => {
          state.showInspect = false
          successDeal('操作成功！')
          getOrderDetail(state.orderId)
          getOrderRecord(state.orderId)
        })
      } else {
        //  佣金分发 再次分佣 和 佣金核减
        json.opType = state.showInspectType == 4 ? 2 : 1
        api.orderCheck(json).then(res => {
          state.showInspect = false
          successDeal('操作成功！')
          getOrderDetail(state.orderId)
          getOrderRecord(state.orderId)
        })
      }
    }

    const submitForward = () => {
      let json = {
        "goodsId": state.forwardForm.goodsId,
        "goodsName": state.forwardForm.goodsName,
        "productId": state.forwardForm.productId,
        "shopId": state.forwardForm.shopId,
        "srcOrderId": state.orderId
      }
      api.orderForward(json).then(res => {
        state.showForward = false
        successDeal('资料转发成功！')
        getOrderDetail(state.orderId)
        getOrderRecord(state.orderId)
      })
    }

    const openPicker = (name) => {
      if (name == '选择供应商') {
        state.pickerTitle = name
        state.showPicker = true
      } else if (name == '选择供应商商品') {
        if (!state.forwardForm.shopId) {
          warningDeal('请先选择供应商！')
        } else {
          let json = {
            shopId: state.forwardForm.shopId
          }
          api.goodsByOperator(json).then(res => {
            res.data.forEach((item, index) => {
              item.goodsId = index + 1
              item.goodsName = item.operator
            })
            state.goodsList = res.data
            state.pickerTitle = name
            state.showPicker = true
          })

        }
      } else if (name == '选择佣金政策') {
        state.pickerTitle = name
        state.showPicker = true
      }
    }

    const handlePicker = (e) => {
      if (e == '选择供应商') {
        let data = pickerRef.value.confirm().selectedOptions[0]
        state.forwardForm.shopName = data.shopName
        state.forwardForm.shopId = data.shopId
        state.showPicker = false
      } else if (e == '选择佣金政策') {
        let data = incomeRef.value.confirm().selectedOptions[0]
        state.inspectForm.income = data.income
        state.inspectForm.recordName = data.recordName
        state.showPicker = false
      }
    }

    const handleCascader = (e) => {
      let data = e.selectedOptions[1]
      state.forwardForm.goodsName = data.goodsName
      state.forwardForm.goodsId = data.goodsId
      state.forwardForm.productId = data.productId
      state.showPicker = false
    }

    const openInspect = (type) => {
      state.showInspectType = type
      if (type == 4) {
        state.inspectForm.checked = 2
      }
      state.showInspect = true
    }

    const closePopup = (name) => {
      if (name == 'inspectForm') {
        state.inspectForm = JSON.parse(JSON.stringify(state.inspectFormDeep))
      }
    }

    const toUploadDetail = (orderId) => {
      router.push({
        path: '/index/uploadDetail',
        query: {
          orderId: orderId,
        }
      })
      return
      if (route.query.pathName) {
        router.replace({
          path: '/middle',
          query: {
            orderId: orderId,
            pathName: '/index/uploadDetail'
          }
        })
      } else {
        router.push({
          path: '/middle',
          query: {
            orderId: orderId,
            pathName: '/index/uploadDetail'
          }
        })
      }
    }

    const toBenefit = (orderId) => {
      router.push({
        path: '/capital/benefit/detail',
        query: {
          incomeOrderId: orderId,
        }
      })
      return
      if (route.query.pathName) {
        router.replace({
          path: '/middle',
          query: {
            incomeOrderId: orderId,
            pathName: '/capital/benefit/detail'
          }
        })
      } else {
        router.push({
          path: '/middle',
          query: {
            incomeOrderId: orderId,
            pathName: '/capital/benefit/detail'
          }
        })
      }
    }

    return {
      ...toRefs(state),
      pickerRef,
      incomeRef,
      handleCopy,
      imagePreview,
      submitInspect,
      validatorPassword,
      openPicker,
      handlePicker,
      handleCascader,
      submitForward,
      getDateTime,
      openInspect,
      closePopup,
      toUploadDetail,
      toBenefit
    }
  }
}
</script>
<style lang='scss' scoped>
.f-detail-order {
  padding-bottom: 59px;
  position: relative;
  .f-steps-group {
    background: #fff;
    padding: 10px;
    color: #373737;
    .f-step {
      display: flex;
      margin-bottom: 20px;
      .f-icon {
        margin-top: 3px;
        width: 20px;
        position: relative;
        .f-line {
          position: absolute;
          background: #a9a9a9;
          width: 1px;
          margin-left: 5px;
        }
      }
    }
    .f-step:last-child {
      margin-top: 25px;
    }
  }
  .f-img1 {
    width: 167px;
    height: 104px;
  }
  .f-title {
    padding: 15px;
    font-size: 14px;
    color: #424242;
    background: #fff;
  }
  .f-btn-box {
    position: fixed;
    bottom: 0px;
    display: flex;
    justify-content: space-around;
    width: 100%;
    height: 59px;
    background: #ffffff;
    border-top: 1px solid #aaaaaa;
    padding: 10px 0;
  }
}
</style>